using Godot;
using System;
using System.Collections.Generic;

namespace ZerAx.Roguelike
{
	public partial class Toaster : VBoxContainer
	{
		private class Toast
		{
			public Control node;
			public float life;
		}

		[Export]
		private PackedScene toastProto;

		[Export]
		private StringName setToastFunc;

		private readonly List<Toast> toasts;
		private readonly Stack<int> freeToastIndices = [];

		public Toaster()
		{
			toasts = [];
			toasts.Capacity = 3;
		}

		public override void _Process(double delta)
		{
			for (var i = 0; i < toasts.Count; i++)
			{
				if (toasts[i].life < 0.0f)
				{
					toasts[i].node.QueueFree();
					freeToastIndices.Push(i);
				}
				else
				{
					toasts[i].life -= (float)delta;
					if (toasts[i].life < 1.0f)
					{
						var modulate = toasts[i].node.Modulate;
						modulate.A = toasts[i].life;
						toasts[i].node.Modulate = modulate;
					}
				}
			}

			while (freeToastIndices.Count > 0)
			{
				var idx = freeToastIndices.Pop();
				toasts.RemoveAt(idx);
			}
		}

		public void MakeToast(string message, float life)
		{
			var node = toastProto.Instantiate<Control>();
			node.Call(setToastFunc, message);

			var toast = new Toast
			{
				node = node,
				life = life,
			};

			if (toasts.Count == toasts.Capacity)
			{
				toasts[0].node.QueueFree();
				toasts.RemoveAt(0);
			}

			AddChild(toast.node);
			toasts.Add(toast);
		}
	}
}